package com.wbw.ssb.service.impl;

import com.github.pagehelper.PageHelper;
import com.wbw.ssb.common.api.ResultCode;
import com.wbw.ssb.common.utils.JwtTokenUtil;
import com.wbw.ssb.dto.UserParam;
import com.wbw.ssb.exception.ApiException;
import com.wbw.ssb.mbg.entity.User;
import com.wbw.ssb.mbg.mapper.UserDynamicSqlSupport;
import com.wbw.ssb.mbg.mapper.UserMapper;
import com.wbw.ssb.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * @Author: guibo
 * @Description:
 * @Date: Created in 0:45 2021/5/19
 * @Modified By:
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    UserMapper userMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    public User getUserByTel(String tel) {
        List<User> users = userMapper.select(c->c
                .where(UserDynamicSqlSupport.tel,isEqualTo(tel)));
        if(users==null||users.isEmpty()){
            throw new ApiException("用户名或密码不正确", ResultCode.FAILED);
        }
        return users.get(0);
    }

    @Override
    public String login(String tel, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(tel);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new ApiException("用户名或密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public Integer register(UserParam userParam) {
        List<User> userList = userMapper.select(c->c
                .where(UserDynamicSqlSupport.tel,isEqualTo(userParam.getTel())));
        if(!userList.isEmpty()){
            throw  new ApiException("该手机已被注册",ResultCode.FAILED);
        }
        User user = new User();
        BeanUtils.copyProperties(userParam,user);
        user.setPermission("员工");
        String encodePassword = passwordEncoder.encode(userParam.getPassword());
        user.setPassword(encodePassword);
        return userMapper.insertSelective(user);
    }

    @Override
    public Integer delete(List<Long> ids) {
        return userMapper.delete(c->c.where(UserDynamicSqlSupport.id,isIn(ids)));
    }

    @Override
    public List<User> list(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.select(c->c
                .where(UserDynamicSqlSupport.name,isLikeWhenPresent(user.getName()).then(s->"%"+s+"%"))
                .and(UserDynamicSqlSupport.tel,isLikeWhenPresent(user.getTel()).then(s->"%"+s+"%"))
                .and(UserDynamicSqlSupport.permission,isEqualToWhenPresent(user.getPermission()))
        );
        userList.forEach(i->i.setPassword("0"));
        return userList;
    }

    @Override
    public Integer update(User user) {
        int count = userMapper.updateByPrimaryKeySelective(user);
        if(count<=0){
            throw new ApiException("更新用户失败", ResultCode.FAILED);
        }
        return count;
    }

}
